<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once(BASEPATH.'core/Model.php');

class Model_crud extends CI_Model {

	public static $tabel;
	public static $tabel_join = array();

	# ================= CREATE =====================

	public static function create($data) {
		$CI =& get_instance();
		$CI->db->insert(static::$tabel, $data);

		if ($CI->db->affected_rows() > 0)
			return $CI->db->insert_id();
		else
			return false;
	}

	# ================== READ =====================

	/**
	 *	model_crud::read()
	 */

	public static function read($filter = array(), $limit=array(), $select='*', $distinct=false, $group_by="", $order_by="") {

		$CI =& get_instance();

		$CI->db->select($select);

		if ($order_by != "")
			$CI->db->order_by($order_by);

		foreach ($filter as $key => $value)
			if (gettype($value)=='array')
				$CI->db->where_in($key, $value);
			else
				$CI->db->where($key, $value);

		if ($distinct)
			$CI->db->distinct();		

		if (count($limit)>0)
			$CI->db->limit($limit[0], $limit[1]);
		
		if ($group_by !== "")
			$CI->db->group_by($group_by);

		foreach (static::$tabel_join as $key => $value)
			$CI->db->join($key, $value, 'left');

		$query = &	$CI->db->get(static::$tabel);
		$hasil = &	$query->result();

		if ($CI->db->affected_rows() > 0){
			return $hasil;
		}
		else
			return false;
	}

	# ================== UPDATE ======================

	public static function update($filter, $data) {
		$CI =& get_instance();

		foreach ($filter as $key => $value)
			$CI->db->where($key, $value);

		$CI->db->update(static::$tabel, $data);

		return ($CI->db->affected_rows() > 0);
	}

	# ================= DELETE ======================

	public static function delete($filter = array()){
		$CI =& get_instance();

		foreach ($filter as $key => $value)
			$CI->db->where($key, $value);

		if ($filter === array())
			$CI->db->truncate(static::$tabel);
		else
			$CI->db->delete(static::$tabel);

	    if ($CI->db->affected_rows() > 0)
	    	return true; 
	    else
	    	return false;
	}

	# ================= COUNT ======================

	public static function count($filter = array()) {
		$CI =& get_instance();

		foreach ($filter as $key => $value)
			$CI->db->where($key, $value);

		return $CI->db->count_all(static::$tabel);
	}
}